package com.test.prolenders.analytics_prolenders.http_prolenders

import android.util.Log
import com.test.prolenders.analytics_prolenders.logger_prolenders.FormatLogger_prolenders
import com.test.prolenders.config_prolenders.Constant_prolenders
import com.test.prolenders.util_prolenders.AESCryptUtil_prolenders
import com.test.prolenders.util_prolenders.http_prolenders.HttpLogger_prolenders
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.sql.DriverManager.println
import java.util.concurrent.LinkedBlockingDeque
import java.util.concurrent.TimeUnit

object HttpHelper_prolenders {

    /** 句柄 */
    private var mHttpPoolExecutorProlenders: HttpPoolExecutor_prolenders? = null

    /** 初始化执行线程 */
    private fun getHttpPoolExecutor(): HttpPoolExecutor_prolenders? {
        if (mHttpPoolExecutorProlenders == null) {
            val availableCoreSize = (Runtime.getRuntime().availableProcessors() / 2)
            val corePoolSize = if (availableCoreSize > 0) availableCoreSize else 1
            println("占用cpu核数：$corePoolSize")

            mHttpPoolExecutorProlenders = HttpPoolExecutor_prolenders(
                corePoolSize = corePoolSize,
                maximumPoolSize = corePoolSize,
                keepAliveTime = corePoolSize.toLong(),
                unit = TimeUnit.SECONDS,
                workQueue = LinkedBlockingDeque()
            ).apply {
                allowCoreThreadTimeOut(true)
            }
        }

        return mHttpPoolExecutorProlenders
    }

    /**
     * 保存数据
     *
     * @param targetUrl 目标路径
     * @param body 数据体
     */
    fun postData(targetUrl: String, body: String) {

        getHttpPoolExecutor()?.execute {
            var httpURLConnection: HttpURLConnection? = null;
            try {
                FormatLogger_prolenders.log(message = "targetUrl:$targetUrl")
                FormatLogger_prolenders.log(message = body)

                httpURLConnection = (URL(targetUrl).openConnection() as HttpURLConnection).apply {
                    setRequestProperty("Connection", "Keep-Alive")
                    setRequestProperty("Charset", "UTF-8")
                    setRequestProperty("Content-Type", "text/plain")
                    setRequestProperty("product", Constant_prolenders.PRODUCT)
//                    setRequestProperty(
//                        "Content-Length",
//                        body.toByteArray().size.toString()
//                    )
                    doOutput = true
                    doInput = true
                    useCaches = false
                    requestMethod = "POST"
                    readTimeout = 180000
                    connectTimeout = 120000
                    outputStream.write(body.toByteArray())
                    outputStream.flush()
                    outputStream.close()
                }

                with(httpURLConnection) {
                    val isSuccess = (responseCode == HttpURLConnection.HTTP_OK)
                    if (isSuccess) {

                        try {
                            // 获取输入流
                            val reader = BufferedReader(InputStreamReader(inputStream))
                            var line: String?
                            val response = StringBuilder()
                            while (reader.readLine().also { line = it } != null) {
                                response.append(line)
                            }
                            val decContent = AESCryptUtil_prolenders.decryptDefault(response.toString())
                            HttpLogger_prolenders.jsonLog(decContent)

                            // 关闭读取器
                            reader.close()
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }

                        println("${responseCode}--${targetUrl}--post success!")
                        Log.d("", "${responseCode}--${targetUrl}--post success!")
                    } else {
                        println("${responseCode}--${targetUrl}--post fail!")
                        Log.d("", "${responseCode}--${targetUrl}--post fail!")
                    }
                }

            } catch (e: Exception) {
                e.printStackTrace();
                println("post fail! ${e.localizedMessage}")

            } finally {
                httpURLConnection?.let {
                    try {
                        it.inputStream.close();
                        it.disconnect();
                    } catch (e: Exception) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}



